/*
 * @Descripttion: 啦啦啦哈哈哈
 * @version: 
 * @Author: lsy
 * @Date: 2021-10-25 15:49:47
 * @LastEditors: lsy
 * @LastEditTime: 2021-10-25 17:07:27
 */
var ws = require("nodejs-websocket");
console.log("开始建立连接...")

var users = [];
var server = ws.createServer(function (conn) {
    conn.on("text", function (str) {
        console.log("收到的信息为:" + str)
        if (str.substring(0, 4) === "user") {
            users.push(conn)
        }
        for (var i in users) {
            if (conn != users[i]) {
                if (str.substring(0, 4) === "user") {
                    users[i].sendText(`用户${str}已上线`);
                } else {
                    users[i].sendText(str);
                }
            }
        }
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接" + reason)
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭" + reason)
    });
}).listen(8001)
console.log("WebSocket建立完毕")